<template>
  <view class="container">
    <!-- 新增打印机表单 -->
    <view class="form-section">
      <u-form ref="formRef" :model="form">
        <u-form-item label="序列号" prop="serialNumber">
          <u-input
              v-model="form.serialNumber"
              placeholder="请输入打印机序列号"
          />
        </u-form-item>
        <u-button
            :loading="loading"
            type="primary"
            @click="handleSubmit"
        >
          新增打印机
        </u-button>
      </u-form>
    </view>
    <!-- 查询结果展示 -->
    <view v-if="printerInfo.id" class="result-section">
      <u-divider text="打印机信息"></u-divider>
      <view class="info-item">
        <text class="label">ID:</text>
        <text>{{ printerInfo.id }}</text>
      </view>
      <view class="info-item">
        <text class="label">序列号:</text>
        <text>{{ printerInfo.serialNumber }}</text>
      </view>
      <view class="info-item">
        <text class="label">使用状态:</text>
        <text>{{ printerInfo.isUsed === 0 ? '未使用' : '已使用' }}</text>
      </view>
      <view class="info-item">
        <text class="label">创建时间:</text>
        <text>{{ printerInfo.createdAt }}</text>
      </view>
    </view>

  </view>
</template>

<script setup>
import {ref, reactive} from 'vue'
import {onLoad} from '@dcloudio/uni-app'


const formRef = ref(null)
const loading = ref(false)
const printerInfo = ref({})

const form = reactive({
  serialNumber: ''
})

// 在页面的 <script setup> 部分添加配置
const config = {
  baseURL: 'http://localhost:8080' // 根据实际服务器地址修改
}

// 修改API请求函数，使用内联配置
// 获取存储的token（根据实际存储方式调整）
const token = uni.getStorageSync('token') || ''

const addPrinter = (data) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: config.baseURL + '/api/printer/add',
      method: 'POST',
      data: data,
      header: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : '' // 添加认证头
      },
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data)
        } else {
          reject(new Error(res.data?.message || '请求失败'))
        }
      },
      fail: (err) => {
        reject(new Error(err.errMsg || '网络请求失败'))
      }
    })
  })
}


const getPrinter = (id) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: config.baseURL + `/api/printer/get/${id}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data)
        } else {
          reject(new Error(res.data?.message || '请求失败'))
        }
      },
      fail: (err) => {
        reject(new Error(err.errMsg || '网络请求失败'))
      }
    })
  })
}


// 提交表单
const handleSubmit = async () => {
  if (!form.serialNumber) {
    uni.showToast({
      title: '请输入序列号',
      icon: 'none'
    })
    return
  }

  try {
    loading.value = true
    console.log('发送请求数据:', {serialNumber: form.serialNumber})
    const response = await addPrinter({serialNumber: form.serialNumber})
    console.log('响应数据:', response)
    printerInfo.value = response
    uni.showToast({
      title: '新增成功',
      icon: 'success'
    })
    form.serialNumber = ''
  } catch (error) {
    console.error('新增失败:', error)
    uni.showToast({
      title: error.message || '新增失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}


// 查询刚新增的打印机（示例：通过ID查询）
const queryPrinter = async (id) => {
  try {
    const response = await getPrinter(id)
    printerInfo.value = response.data
  } catch (error) {
    uni.showToast({
      title: '查询失败',
      icon: 'none'
    })
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
}

.form-section {
  background: #fff;
  padding: 30rpx;
  border-radius: 10rpx;
  margin-bottom: 30rpx;
}

.result-section {
  background: #fff;
  padding: 30rpx;
  border-radius: 10rpx;
}

.info-item {
  display: flex;
  margin-bottom: 20rpx;
  padding: 10rpx 0;
}

.label {
  font-weight: bold;
  width: 150rpx;
  color: #333;
}
</style>
